<?php 
/**
 * 
 * controlador de sms
 * @author Natanael 
 * 
 */
class Smsinternos extends Controller{

      public function __construct()
      {
          parent::Controller();
          $this->load->library(array('chgraficos','chcalendario','chcompany'));
          $this->load->model(array('smssetupci','mscript','mcompania','smsnotificacion',
                                   'mprocesos','headerci','detalleci','metapas','vistaproseso'));         
         
      }
      
      public function index()
      {   	
        	$this->load->view('main', array('content_page' => 'headerci','menutop'=>'5'));
      }
      
      
      public function smsSetupCI($error = false)
      {
      	   	 
      	 $script = $this->mscript->loadScript();
      	 $registro = $this->smssetupci->loadRegistro();
      	 $registro = $registro[0];
         $this->load->view('main', array('content_page'     => 'smssetupci',
                                         'menutop'          => 1,
                                         'script'           => $script,
                                         'registro'         => $registro,
                                         'error'            => $error));
      }

      
      public function sevesetup()
      {
         if (is_numeric($this->input->post('edesde')) && is_numeric($this->input->post('ehasta'))){
         	
         	 $data = array(
         	               "scriptFirma"    => $this->input->post('firma'),
         	               "etapaDesde"     => $this->input->post('edesde'),
         	               "etapaHasta"     => $this->input->post('ehasta'),
         	               "scriptEmail"     => $this->input->post('email'));
         	
         	 if ($this->smssetupci->edit($data) != false)
         	     redirect("/smsinternos/smssetupci/2");            
         	              
         }
        
              redirect("/smsinternos/smssetupci/1");
      }
      
      public function generadorDeSmsDatoFirma()
      {
      	
      	$smsSetup = $this->smssetupci->loadRegistro();
      	$smsSetup = $smsSetup[0];
         
      	$script =$this->mscript->LoadRegistroById($smsSetup->getScriptFirma());
      	   	
      	$loadCompany = $this->mcompania->LoadCompanias(); 
          
      	$companyFrima = $this->loadScriptByEstapa($loadCompany, $script->getBodyScript(),10, $smsSetup->getEtapaDesde(), $smsSetup->getEtapaHasta());
        $companyDatos = $this->loadScriptByEstapa($loadCompany, $script->getBodyScript(),11, $smsSetup->getEtapaDesde(), $smsSetup->getEtapaHasta());	
        
        $smsData = array_merge($companyFrima,$companyDatos);

        echo "<pre>";
      	  print_r($smsData);
      	echo "</pre>";
      
      }
      
      private function loadScriptByEstapa($loadCompany, $scritTex, $etapa, $dia1, $dia2)
      {
      	    $objetoTrue = array();
      	    $objetoTrue[] = array(0, "8298720435",$scritTex);
      	    foreach ($loadCompany as $objetoCompany){
      	    	     
      	             $lastProsesso = $this->mprocesos->loadLastProceso($objetoCompany->getIdCompania());
      	             
      	             $loadProsesso = $this->mprocesos->loadProcesosByArray(array("IdProceso" => $lastProsesso, 
      	                                                                         "IdEtapa"   => $etapa));   

      	            
      	        if (is_array($loadProsesso)){
      	               $loadProsesso = $loadProsesso[0];
      	               $diasEstapa = $this->chcalendario->calcularDias($loadProsesso->getFechaSys());
      	             
      	               if ($diasEstapa >= $dia1 && $diasEstapa <= $dia2) {
      	             	      $company = $this->mcompania->LoadCompaniaById($objetoCompany->getIdCompania());
      	             	      
      	             	      $expTel = array('/\ /', '/\-/','/\//','/\./','/\,/','/([A-Z])/','/([a-z])/');
      	             	      $telefono1 = trim(preg_replace($expTel,"",$company->getTelefono1Compania()));
      	             	      $telefono2 = trim(preg_replace($expTel,"",$company->getTelefono2Compania()));
      	             	            
      	             	      if (strlen($telefono1) > 9){

      	             	      	   $scritTexTrue = preg_replace('/\XXXNOMBRE/', $company->getContacto(), $scritTex);
      	             	      	   $scritTexTrue = preg_replace('/\XXXREFERENCIA/', $company->getNombreCompania(), $scritTexTrue);
                                 
      	             	           $objetoTrue[] = array($objetoCompany->getIdCompania(),$telefono1,$scritTexTrue,$etapa);
      	             	      }
      	             	      
      	             	      if (strlen($telefono2) > 9){
      	             	      
      	             	      	  $scritTexTrue = preg_replace('/\XXXNOMBRE/', $company->getContacto(), $scritTex);
      	             	      	  $scritTexTrue = preg_replace('/\XXXREFERENCIA/', $company->getNombreCompania(), $scritTexTrue);
                                 
      	             	          $objetoTrue[] = array($objetoCompany->getIdCompania(),$telefono2,$scritTexTrue,$etapa);
      	             	      
      	             	      }
 
      	               }	
      	         
      	         }
      	              
      	   }
      	    $objetoTrue[] = array(0, "8298720435",$scritTex);
      	   
      	   return $objetoTrue;
      }
      
      /**
       * 
       * Imprime data Gris Datos de Header
       * 
       */
      
      public function dataheader()
      {
      
          $page = $this->input->post('page') ? $this->input->post('page') : 1; // Pagina Actual o 1 por default
		  $sortname = $this->input->post('sidx') ? $this->input->post('sidx') : 'Date'; // Columna para el order by
		  $sortorder = $this->input->post('sord') ? $this->input->post('sord') : 'desc'; // Orden (asc|desc)
		  $limit = $this->input->post('rows') ? $this->input->post('rows') : 100;
		  $start = $limit * $page - $limit;
		  if($start < 0) $start = 0;
  
		    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		    header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
		    header("Cache-Control: no-cache, must-revalidate" );
		    header("Pragma: no-cache" );
		    
          $contactoSearch = false; 

	      $records = $this->headerci->loadRegistro(false ,$start, $limit, $sortname, $sortorder);

	      
		  $totalRecords = count($records);
		

		  $totalPages = ceil($totalRecords/$limit);
		     if ($page > $totalPages) $page = $totalPages;

		   $json_output = array(
		       'page'		=> $page,
		       'total'		=> $totalPages,
		       'records'	=> $totalRecords,
		       'rows'		=> array()
		  );

		  if($records != false) {
		  	  foreach($records as $k) {
                  
		  	  
		  	  	$data = explode("-",$k->getData());
		  	  	
		  	  	$data = $data[1].'/'.$data[2].'/'.$data[0];
		  	  	
				$arr = $json_output['rows'][] = array(
				               'idsms'           => $k->getIdSms(),
				               'smsdata'         => $data.' '.$k->getTime(),
				               'smscnt'          => $k->getSmsEnviados(),
				               'Type'            => $k->getSmsType()
				        			              
				 );
				
			}
		}

		$a=json_encode($json_output);
		$a=str_replace('\\','',$a);
		echo $a;
		
      
      }
      
      public function datadetalles()
      {
      
         $id = $this->input->post('iddetalle');
         
          $page = $this->input->post('page') ? $this->input->post('page') : 1; // Pagina Actual o 1 por default
		  $sortname = $this->input->post('sidx') ? $this->input->post('sidx') : 'IdSmsHeaderCi'; // Columna para el order by
		  $sortorder = $this->input->post('sord') ? $this->input->post('sord') : 'desc'; // Orden (asc|desc)
		  $limit = $this->input->post('rows') ? $this->input->post('rows') : 10;
		  $start = $limit * $page - $limit;
		  if($start < 0) $start = 0;
  
		    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		    header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
		    header("Cache-Control: no-cache, must-revalidate" );
		    header("Pragma: no-cache" );
         
		    
		    
	      $records = $this->detalleci->loadRegistro(array("IdSmsHeaderCi"   => $id));
		
		  $totalRecords = count($records);
		

		  $totalPages = ceil($totalRecords/$limit);
		     if ($page > $totalPages) $page = $totalPages;

		   $json_output = array(
		       'page'		=> $page,
		       'total'		=> $totalPages,
		       'records'	=> $totalRecords,
		       'rows'		=> array()
		  );
		    
		  
		  if($records != false) {
		  	  foreach($records as $k) {
		  	  	
		  	  	$etapa = $this->metapas->LoadEtapaById($k->getEtapa());
		  	  	
				$arr = $json_output['rows'][] = array(
				               'Referencia'        => $k->getReferencia(),
				               'Telefono'          => $k->getTelefono(),
				               'Contacto'          => $k->getContacto(),
				               'Etapa'             => $etapa->GetNombre()
				        			               
				 );
				
			}
		  }

		    $a=json_encode($json_output);
		    $a=str_replace('\\','',$a);
		    echo $a;
      
      }
      
      public function smsDataCheck()
      {
      	
      	  $page = $this->input->post('page') ? $this->input->post('page') : 1; // Pagina Actual o 1 por default
		  $sortname = $this->input->post('sidx') ? $this->input->post('sidx') : 'IdCompania'; // Columna para el order by
		  $sortorder = $this->input->post('sord') ? $this->input->post('sord') : 'desc'; // Orden (asc|desc)
		  $limit = $this->input->post('rows') ? $this->input->post('rows') : 10;
		  $start = $limit * $page - $limit;
		  if($start < 0) $start = 0;
  
		    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		    header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
		    header("Cache-Control: no-cache, must-revalidate" );
		    header("Pragma: no-cache" );
         
		    
		  $arrayWhere = array(10,11);
	      $records = $this->vistaproseso->loadProsseso($arrayWhere);
		
		  $totalRecords = count($records);
		

		  $totalPages = ceil($totalRecords/$limit);
		     if ($page > $totalPages) $page = $totalPages;

		   $json_output = array(
		       'page'		=> $page,
		       'total'		=> $totalPages,
		       'records'	=> $totalRecords,
		       'rows'		=> array()
		  );
		    
		  
		  if($records != false) {
		  	  foreach($records as $k) {
		  	  
		  	  	$date = explode(" ",$k->getFechaSysProceso());
		  	  	$data = explode("-",$date[0]);
		  	  	
		  	  	$etapa = $this->metapas->LoadEtapaById($k->getIdEtapa());
		  	  	
		  	  	$dias = $this->chcalendario->calcularDias($k->getFechaSysProceso());
		  	  	
				$arr = $json_output['rows'][] = array(
				               'IdCompania'         => $k->getIdCompany(),
				               'IdProceso'          => $k->getIdProceso(),
				               'NombreCompania'     => $k->getNombreCompania(),
				               'Telefono1Compania'  => $k->getTelefono1Compania(),
				               'Telefono2Compania'  => $k->getTelefono2Compania(),
				               'Contacto'           => $k->getContacto(),
				               'Etapa'              => $etapa->GetNombre(),
				               'FechaSysProceso'    => $data[1].'/'.$data[2].'/'.$data[0],
				               'Dias'               => $dias);
				
			}
		  }

		    $a=json_encode($json_output);
		    $a=str_replace('\\','',$a);
		    echo $a;
      
      }
      
      public function smsCheck()
      {     
        $this->load->view('main', array('content_page' => 'smslote','menutop'=>8));
      }
      
      public function lotedata($dataObjeto = false)
      {
         $arrayObjeto = explode("-",$dataObjeto);
         
         if ($dataObjeto == false) {
             	redirect('smsinternos/smscheck');
         }
         
         $this->db->truncate('SC_CheckDF');
         foreach ($arrayObjeto as $k){
         	
         	 
              $this->db->insert('SC_CheckDF', array("IdCompany"   => $k));     
         }
         
         $this->chcompany->hacerPing("http://ibc-help.com/sms/checkci.php");
        // file_get_contents("http://ibc-help.com/sms/checkci.php");
         redirect('controlinterno'); 	
         
      }
      
      public function smsNotificacion($error = false)
      {
      	 $registro = $this->smsnotificacion->loadQueyArray();
         $this->load->view('main', array('content_page'  => 'smsnotificacion',
                                         'menutop'       => 5, 
                                         'error'         => $error,
                                         'registro'      => $registro));
      }
      
      public function seveNotificacion()
      {
          $telefono = $this->input->post('telefono');
          $mensaje = $this->input->post('mensaje');
          
          if(strlen($telefono) != 10){
          	  $this->session->set_flashdata('mensaje', 'Ha ocurrido un error en el campo de telefono, la forma correcta de el telefono es 8092221111');
              redirect('smsinternos/smsnotificacion/1'); 
          }
          
          $arrayData = array("Telefono"     => $this->input->post("telefono"),
                             "Mensajes"     => $this->input->post("mensaje"),
                             "Mail"         => $this->input->post("email"));
          
          if ($this->smsnotificacion->editRegistro($arrayData) == true){
              $this->session->set_flashdata('mensaje', 'La operaci&oacute;n se ha completado exitosamente');
              redirect('smsinternos/smsnotificacion/2');
          }else{                  
               $this->session->set_flashdata('mensaje', 'Ha ocurrido un error en la consulta, por favor vuelva a intentar');
               redirect('smsinternos/smsnotificacion/1'); 
          }
      }
      

}